package com.jrx.anytxn.investor.mq;

import com.jrx.anytxn.common.exception.TxnRuntimeException;
import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.investor.bean.InvestorCreditBean;
import com.jrx.anytxn.investor.constant.TransBizConstant;
import com.jrx.anytxn.investor.handler.IInvestorCreditHandler;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RocketMQMessageListener(
        topic = TransBizConstant.MQ_INVESTOR_CREDIT_TOPIC + "${spring.cloud.nacos.discovery.metadata.currentVersion}",
        consumerGroup = TransBizConstant.MQ_INVESTOR_CREDIT_GROUP + "${spring.cloud.nacos.discovery.metadata.currentVersion}",
        consumeThreadMax = 10)
public class InvestorCreditMqConsumerService implements RocketMQListener<String> {

    private static final Logger logger = LoggerFactory.getLogger(InvestorCreditMqConsumerService.class);

    @Autowired
    private IInvestorCreditHandler investorCreditHandler;

    @Override
    public void onMessage(String jSonMessage){

        logger.info("MQ消费端获取到联合贷授信请求 ：{}",jSonMessage);

        // json转换成并bean
        List<InvestorCreditBean> beans;
        try {
            beans = JsonUtils.json2list(jSonMessage, InvestorCreditBean.class);
        } catch (Exception e) {
            logger.error("MQ消费端JSon转换异常 ：{}",e);
            throw new TxnRuntimeException("MQ消费端JSon转换异常");
        }

        // 联合贷授信
        try {
            investorCreditHandler.investorCredit(beans);
        } catch (Exception e) {
            logger.error("MQ消费端，联合贷授信处理异常异常：{}", e);
            throw new TxnRuntimeException("合作行授信异常");
        }
    }

}
